<?php

class AdminController extends ActionController {
    /**
     * 用户列表
     */
    public function actionList() {
        if (Yii::app()->request->isAjaxRequest) {
            $page = Yii::app()->request->getPost('page', 1);
            $limit = Yii::app()->request->getPost('limit', 10);
            $page_data = Admin::model()->getPageList($page, $limit);
            $this->jsonResponse($page_data);
        } else {
            $this->render('list');
        }
    }

    /**
     * 新建用户
     */
    public function actionCreate() {
        if (Yii::app()->request->isPostRequest) {
            $data = array(
                'username' => Yii::app()->request->getPost('username'),
                'role_id' => Yii::app()->request->getPost('role_id', 0),
            );
            $admin = new Admin();
            $is_success = $admin->createAdmin($data);
            if ($is_success === false) {
                $this->error($admin->getErrors());
            }
            $this->success('用户创建成功,默认密码：888888');
        } else {
            $role_list = Role::model()->findAll();
            $this->render('create', array('role_list' => $role_list));
        }
    }

    /**
     * 编辑用户
     */
    public function actionModify() {
        $id = Yii::app()->request->getParam('id');
        if (empty($id)) {
            $this->error('参数非法');
        }
        $admin = Admin::model()->findByPk($id);
        if ($admin === null) {
            $this->error('用户不存在');
        }
        if (Yii::app()->request->isPostRequest) {
            $data = array(
                'password' => Yii::app()->request->getPost('password', ''),
                'role_id' => Yii::app()->request->getPost('role_id', 0),
            );
            $is_success = $admin->modifyAdmin($data);
            if ($is_success === false) {
                $this->error($admin->getErrors());
            }
            $this->success('用户修改成功');
        } else {
            $role_list = Role::model()->findAll();
            $this->render('modify', array('role_list' => $role_list,'admin'=>$admin));
        }
    }

    /**
     * 删除用户
     */
    public function actionRemove() {
        if (Yii::app()->request->isAjaxRequest) {
            $id = Yii::app()->request->getQuery('id');
            if (empty($id)) {
                $this->error('参数非法');
            }
            $admin = Admin::model()->findByPk($id);
            if ($admin === null) {
                $this->error('用户不存在');
            }
            $is_success = $admin->remove();
            if ($is_success === false) {
                $this->error($admin->getErrors());
            }
            $this->success('用户删除成功');
        }
    }
}